package cn.itcast.service;

import cn.itcast.utils.HttpClientUtil;
import com.github.wxpay.sdk.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * @author coolbook
 * @ClassName WxSerivce
 * @Description TODO
 * @Date 14:25 2021/11/17
 * @Version 1.0
 */
@Service
public class WxSerivce {
    @Value("${wx.pay.appid}")
    private String appid;
    @Value("${wx.pay.partner}")
    private String partner;
    @Value("${wx.pay.partnerkey}")
    private String partnerkey;
    @Value("${wx.pay.notify_url}")
    private String notifyurl;

    /**
     * 生成二维码和支付页面
     *
     * @param orderId
     * @return
     */
    public String createCode(String orderId) {
        try {
            Map<String, String> map = new HashMap<>(16);
            map.put("appid", appid);
            map.put("mch_id", partner);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body", "health,cool");
            //订单号
            map.put("out_trade_no", orderId);
            //金额
            map.put("total_fee", "1");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", notifyurl);
            map.put("trade_type", "NATIVE");
            String sign = WXPayUtil.generateSignedXml(map, partnerkey);
            map.put("sign", sign);
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //提交方式
            HttpClientUtil httpClientUtil = new HttpClientUtil(url);
            httpClientUtil.setHttps(true);
            httpClientUtil.setXmlParam(sign);
            httpClientUtil.post();
            String content = httpClientUtil.getContent();
            Map<String, String> map1 = WXPayUtil.xmlToMap(content);
            String url1 = map1.get("code_url");
            return url1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
